package com.wxlsoft.config;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.wxlsoft.config.model.ConfigFileResource;
import com.wxlsoft.config.model.ConfigFileType;
import com.wxlsoft.config.model.ConfigFileTypeValue;
import com.wxlsoft.ui.conflist.CheckNode;

import cn.hutool.core.io.resource.FileResource;


public class ConfigNodeContext {

	private static CheckNode rootNode;
	
	public static void setFileNode(CheckNode filenode) {
		rootNode = filenode;
	}
	
	public static CheckNode getRootNode() {
		return rootNode;
	}
	
	public static Collection<ConfigFileResource> getConfigFileResource() {
		if (Objects.isNull(rootNode)) return Collections.emptyList();
		
		Map<String, ConfigFileResource> collector = new HashMap<>();
		loopParse(collector, rootNode);
		return collector.values();
	}
	
	private static void loopParse(Map<String, ConfigFileResource> collector, CheckNode fileNode) {
		File file = fileNode.getFile();
		if (file.isDirectory()) {
			Enumeration children = fileNode.children();
			while (children.hasMoreElements()) {
				CheckNode cn = (CheckNode) children.nextElement();
				loopParse(collector, cn);
			}
		} else {
			if (fileNode.isSelected()) {
				ConfigFileTypeValue value = ConfigFileType.entity(file.getName());
				if (Objects.nonNull(value)) {
					ConfigFileResource resource = collector.computeIfAbsent(value.getService(), (k) -> new ConfigFileResource(value.getService(), value.getVersion()));
					FileResource fileResource = new FileResource(file);
					switch (value.getType()) {
						case SERVICE: resource.setService(fileResource);
							break;
						case CONSUMER_PACKER: resource.setClientOut(fileResource);
							break;
						case CONSUMER_UNPACK: resource.setClientIn(fileResource);
							break;
						case PROVIDER_UNPACK: resource.setProdIn(fileResource);
							break;
						case PROVIDER_PACKER: resource.setProdOut(fileResource);
							break;
						default:
							break;
					}
				}
			}
		}
	}
	
}
